var MultipleUploader = {};

MultipleUploader.config = {
    SELECTOR_WRAPPER: 'div.system-upload-field-multiple-img-wrapper',
    SELECTOR_ITEM: 'div.system-upload-field-multiple-item',
    SELECTOR_ITEM_NAME: 'span.system-upload-field-multiple-name',
    SELECTOR_ITEM_STATE: 'span.system-upload-field-multiple-state'
};

MultipleUploader.updateField = function ($field, $wrapper) {
    var fileList = [];
    $wrapper.find(MultipleUploader.config.SELECTOR_ITEM).each(function () {
        var info = MultipleUploader.readFileInfoFromItem($(this));
        if (info.state == '完成') {
            fileList.push({
                name: info.name,
                url: info.url
            })
        }
    });
    $field.val(JSON.stringify(fileList));
};

MultipleUploader.updateState = function ($field, $wrapper, name, url, state) {
    var $item = null;
    $wrapper.find(MultipleUploader.config.SELECTOR_ITEM).each(function () {
        var _f_name = $(this).find(MultipleUploader.config.SELECTOR_ITEM_NAME).text();
        if (_f_name == name) {
            $item = $(this);
        }
    });
    if ($item != null) {
        $item.attr('rel-url', url);
        $item.find(MultipleUploader.config.SELECTOR_ITEM_STATE).text(state);
    }
};

MultipleUploader.createRow = function ($field, $wrapper, fileInfo, state) {
    var $fileDiv = $('<div class="system-upload-field-multiple-item"></div>');
    $fileDiv.attr("rel-url", fileInfo.url);
    $fileDiv.append('<span class="system-upload-field-multiple-name">' + fileInfo.name + '</span>');
    var $fileStateSpan = $('<span class="system-upload-field-multiple-state">' + state + '</span>');
    var $fileUpBtn = $('<button>上移</button>');
    var $fileDownBtn = $('<button>下移</button>');
    var $fileDelBtn = $('<button>删除</button>');
    $fileUpBtn.click(function () {
        MultipleUploader.moveUp($field, $wrapper, $(this).closest(MultipleUploader.config.SELECTOR_ITEM));
        return false;
    });
    $fileDownBtn.click(function () {
        MultipleUploader.moveDown($field, $wrapper, $(this).closest(MultipleUploader.config.SELECTOR_ITEM));
        return false;
    });
    $fileDelBtn.click(function () {
        $(this).closest(MultipleUploader.config.SELECTOR_ITEM).remove();
        MultipleUploader.updateField($field, $wrapper);
        return false;
    });
    $fileDiv.append($fileStateSpan);
    $fileDiv.append($fileUpBtn);
    $fileDiv.append($fileDownBtn);
    $fileDiv.append($fileDelBtn);
    $wrapper.append($fileDiv);
};

MultipleUploader.initMultipleUploader = function ($element) {
    var dataFor = $element.attr('data-for');
    var $wrapper = $element.next(MultipleUploader.config.SELECTOR_WRAPPER);
    var $field = $('[name="' + dataFor + '"]');

    var fileList = [];
    if ($field.val() != '') {
        fileList = JSON.parse($field.val());
    }
    _.each(fileList, function (fileInfo) {
        MultipleUploader.createRow($field, $wrapper, fileInfo, '完成');
    });

    $element.change(function () {
        var $this = $(this);
        if ($this.val() != '') {
            if (MultipleUploader.checkDupeFileName($this, $field)) {
                layer.msg('请勿上传同名文件！');
                return false;
            }
            _.each($this[0].files, function (f, i) {
                MultipleUploader.createRow($field, $wrapper, {name: f.name, url: ''});
                var formData = new FormData();
                formData.append("file", f);
                $.ajax({
                    url: rootPath + '/system/upload.shtml',
                    type: 'POST',
                    cache: false,
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        MultipleUploader.updateState($field, $wrapper, f.name, (eval(res)), '完成');
                        MultipleUploader.updateField($field, $wrapper);
                    },
                    error: function (err) {
                        MultipleUploader.updateState($field, $wrapper, f.name, (eval(res)), '失败');
                        MultipleUploader.updateField($field, $wrapper);
                    }
                });
            });
        }
    });
};

MultipleUploader.init = function ($element) {
    $element.each(function () {
        MultipleUploader.initMultipleUploader($(this));
    })
};

MultipleUploader.checkDupeFileName = function ($element, $field) {
    var fileList = [];
    if ($field.val() != '') {
        fileList = JSON.parse($field.val());
    }
    var dupeFlag = false;
    _.each($element[0].files, function (f1) {
        if (_.find(fileList, function (f2) {
            return f1.name == f2.name;
        }) != null) {
            dupeFlag = true;
        }
    });
    return dupeFlag;
};

MultipleUploader.moveUp = function ($field, $wrapper, $item) {
    var $itemPrev = $item.prev(MultipleUploader.config.SELECTOR_ITEM);
    if ($itemPrev.length > 0) {
        MultipleUploader.swapItem($itemPrev, $item);
        MultipleUploader.updateField($field, $wrapper);
    }
};

MultipleUploader.moveDown = function ($field, $wrapper, $item) {
    var $itemNext = $item.next(MultipleUploader.config.SELECTOR_ITEM);
    if ($itemNext.length > 0) {
        MultipleUploader.swapItem($item, $itemNext);
        MultipleUploader.updateField($field, $wrapper);
    }
};

MultipleUploader.swapItem = function ($item1, $item2) {
    var info1 = MultipleUploader.readFileInfoFromItem($item1);
    var info2 = MultipleUploader.readFileInfoFromItem($item2);
    MultipleUploader.setFileInfoForItem($item1, info2);
    MultipleUploader.setFileInfoForItem($item2, info1);
};

MultipleUploader.readFileInfoFromItem = function ($item) {
    return {
        name: $item.find(MultipleUploader.config.SELECTOR_ITEM_NAME).text(),
        url: $item.attr('rel-url'),
        state: $item.find(MultipleUploader.config.SELECTOR_ITEM_STATE).text()
    };
};

MultipleUploader.setFileInfoForItem = function ($item, info) {
    $item.find(MultipleUploader.config.SELECTOR_ITEM_NAME).text(info.name);
    $item.attr('rel-url', info.url);
    $item.find(MultipleUploader.config.SELECTOR_ITEM_STATE).text(info.state);
};
